const Schema = require('mongoose/lib/schema');
const db = require('./conn');
const seedrandom = require('seedrandom');
const random = seedrandom();

let counter = 1;
const nextId = () => counter++;
const getRandom = () => Math.floor(random() * 500)

const Random = {type: Number, default: getRandom};
const CountedId = {type: Number, default: nextId};

const QuestionSchema = new Schema({
  id: CountedId,
  random: Random,
  content: String,
  answers: [{
    id: Number,
    content: String,
    isCorrect: {type: Boolean, default: false}
  }],
  count_answered: {type: Number, default: 0},
  count_correct: {type: Number, default: 0}
});

QuestionSchema.pre('update', function (next) {
  this.random = getRandom();
  next()
});

QuestionSchema.pre('save', function (next) {
  this.random = getRandom();
  next()
});

const Question = db.model('Question', QuestionSchema);

module.exports = Question;

Question.find({id: {$gt:0}}).sort({id: -1}).then(([first, ...others]) => {
  if (first)
    counter = first.id +1;
});
